package com.ls.thread.xgCarthroughBridge;

public class CarThroughLightThread implements Runnable{

	/**
	 * java多线程实现车辆 通过 红绿灯
	 * 	1.一次通过一辆
	 * @param light	初始化红绿灯：true（绿灯），flase（红灯）
	 * @param count	车的数量
	 */
	public CarThroughLightThread(boolean light, int count) {
		this.light = light;
		this.count = count;
		temp = count;
	}

	/**
	 * 灯色：true表示绿灯；false表示红灯
	 */
	private boolean light;
	
	/**
	 * 红绿灯过10辆车
	 */
	private int count;
	private int temp ;

	@Override
	public void run() {
		boolean jgdge = true;
		while(jgdge){
			jgdge = carGo();
		}
		System.out.println("---车都全部通过了---");
	}
	
	private synchronized boolean carGo(){
		
		if(count>0){
			throughACar();	//通过一辆车
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return true;
		}else{
			return false;
		}
	}
	
	private void throughACar(){
		if(!light){
			int time = 2;
			//红灯时：等5s转换 绿灯
			while(time > 0){
				System.out.println("红灯：还剩"+time+"秒");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				time--;
			}
			light = !light;		//变绿灯
			go();
		}else{
			go();
		}
		
	}

	/**
	 * 过一辆车
	 */
	private void go() {
		//车通过
		System.out.println("--绿灯："+Thread.currentThread().getName()+":过了......（第"+(temp-count+1)+"辆）");
	
		//车辆通过：用时1s
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		light = !light;		//车过后，变红灯
		count--;
	}
	
}
